import { useState, useRef, useEffect } from "react";
import { Button, Space } from "antd";
import lottie, { AnimationItem, AnimationSegment } from "lottie-web";
import "@/tailwind-variables.less";

import styles from "./index.module.less";

export const LottieWebDemo = (props: { jsonPath: string }) => {
  const { jsonPath } = props;
  const [showButtons, setShowButtons] = useState(false); // 新增状态用于控制按钮显示隐藏
  const [stage, setStage] = useState(1);
  const lottieRef = useRef<any>(null);
  const animationInstance = useRef<AnimationItem | null>(null);
  const stageArrayRef = useRef<AnimationSegment[]>([]);
  const timerRef = useRef<any>();
  const [animate, setAnimate] = useState(styles["animate__slideDownCustom"]);

  useEffect(() => {
    // 初始化动画
    animationInstance.current = lottie.loadAnimation({
      container: lottieRef.current,
      renderer: "svg",
      loop: false,
      autoplay: false,
      path: jsonPath,
    });

    if (animationInstance.current) {
      animationInstance.current.addEventListener("DOMLoaded", function () {
        if (animationInstance.current) {
          // 获取总帧数
          const totalFrames = animationInstance.current.getDuration(true);
          console.log("totalFrames:", totalFrames);
          /**
           * ui切的图，第一部分和第三部分为15帧
           */
          stageArrayRef.current = [
            [0, 15],
            [16, totalFrames - 16],
            [totalFrames - 15, totalFrames],
          ];
        }
      });

      animationInstance.current.addEventListener("segmentStart", (event) => {
        if (event.firstFrame === stageArrayRef.current[0][0]) {
          // 防止隐藏按钮的操作还未执行，印象移入移出的动画，这里将定时器置为null
          timerRef.current = null;
          setStage(1);
        }
        if (event.firstFrame === stageArrayRef.current[1][0]) {
          setStage(2);
        }
        if (event.firstFrame === stageArrayRef.current[2][0]) {
          setStage(3);
          // 在第三阶段，同步执行隐藏按钮的操作
          handleHideButtons();
        }
      });
    }

    // 清除动画实例
    return () => animationInstance?.current?.destroy();
  }, []);

  const handleMouseEnter = () => {
    handleShowButtons();
    const animation = animationInstance.current;
    if (!animation) return;

    // 播放第一阶段和第二阶段
    animation.playSegments(
      [stageArrayRef.current[0], stageArrayRef.current[1]],
      true
    );
  };

  const handleMouseLeave = () => {
    const animation = animationInstance.current;
    if (!animation) return;

    // 获取总帧数
    const currentFrame = animationInstance?.current?.currentFrame ?? 0;
    // 如果当前帧在第一阶段范围内，继续播放第一阶段完
    if (stage === 1) {
      animation.playSegments(
        [[currentFrame, stageArrayRef.current[0][1]], stageArrayRef.current[2]],
        true
      );
    }
    if (stage === 2) {
      animation.playSegments([stageArrayRef.current[2]], true);
    }
  };

  const handleShowButtons = () => {
    setShowButtons(true);
    setAnimate(styles["animate__slideUpCustom"]);
  };

  const handleHideButtons = () => {
    setAnimate(styles["animate__slideDownCustom"]);
    // 移入移出是0.25s,这里显隐给0.5s，确保不影响移入移出的动画
    timerRef.current = setTimeout(() => {
      setShowButtons(false);
    }, 500);
  };

  return (
    <div
      onMouseEnter={handleMouseEnter}
      onMouseLeave={handleMouseLeave}
      className="relative w-[500px] overflow-hidden rounded-[26px] text-[#fff]"
    >
      <div
        className="mb-[-5px] h-auto min-h-[200px] w-full min-w-[300px]"
        style={{ backgroundColor: "rgba(25, 30, 38, 1)", borderRadius: "26px" }}
        ref={lottieRef}
      />
      {showButtons && (
        <Space
          className={`${animate}`}
          style={{
            position: "absolute",
            bottom: "-60px",
            left: "30px",
          }}
        >
          <Button
            className="text-[#fff]"
            style={{
              border: "0px",
              fontSize: "18px",
              width: "120px",
              height: "44px",
              borderRadius: "60px",
              background:
                " linear-gradient(90deg, rgba(79, 120, 255, 1) 0%, rgba(49, 97, 255, 1) 100%)",
            }}
          >
            去创作
          </Button>
          <a href="#" target="__blank">
            <Button
              className="text-[#fff]"
              style={{
                border: "0px",
                fontSize: "18px",
                width: "120px",
                height: "44px",
                borderRadius: "60px",
                background: "rgba(46, 51, 59, 0.7)",
              }}
            >
              使用手册
            </Button>
          </a>
        </Space>
      )}
    </div>
  );
};
